from flask import g
from flask import render_template, jsonify
from flask import request
from flask import session

from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blue
from flask import Flask, current_app
from info.utils.common import user_login_data

@index_blue.route("/favicon.ico")  # "/favicon.ico":网站的图标
def show_ico():
    # current_app：当前的代理对象
    return current_app.send_static_file("news/favicon.ico")


@index_blue.route("/")
@user_login_data
def index():
    user = g.user
    news = News.query.order_by(News.clicks.desc()).limit(10)
    new_list = []
    for news_mode in news:
        new_list.append(news_mode.to_dict())
    category = Category.query.all()
    category_list = []

    for category_mode in category:
        category_list.append(category_mode.to_dict())
    data = {"user_info": user.to_dict() if user else None,
            "click_news_list":new_list,
            "categories":category_list
            }
    return render_template("news/index.html", data=data)

@index_blue.route("/news_list")
def news_blue():
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)
    # 经过http协议传递之后，这些值都变成字符串
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:  # 如果传过来的参数不符合要求，强转
        current_app.logger.error(e)
        cid = 1
        page = 1
        per_page = 10
    filter=[News.status == 0]
    if cid != 1:
        filter.append(News.category_id == cid)

    # if cid == 1:
    #     paginate = News.query.order_by(News.create_time.desc()).paginate(page, per_page, False)
    # else:
    #     paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page, per_page,False)
    paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page, per_page,False)

    items = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    news_list = []
    for item in items:
        news_list.append(item.to_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_dict_li": news_list
    }
    return jsonify(errno=RET.OK, errmsg="成功", data=data)